using MediatR;
using B.S.BasicData.Infrature;
using B.S.BasicData.Domain;
using B.S.BasicData.EroorCode;

namespace B.S.BasicData.Api
{
    public class SlaughterEnterpriseInfoUpdateHandler : IRequestHandler<SlaughterEnterpriseInfoUpdateRequest, ApiResult<SlaughterEnterpriseInfo>>
    {
        private readonly IBaseRepository<SlaughterEnterpriseInfo> _repository;

        public SlaughterEnterpriseInfoUpdateHandler(IBaseRepository<SlaughterEnterpriseInfo> repository)
        {
            _repository = repository;
        }

        public async Task<ApiResult<SlaughterEnterpriseInfo>> Handle(SlaughterEnterpriseInfoUpdateRequest request, CancellationToken cancellationToken)
        {
            try
            {
                // 参数验证
                if (request.Id <= 0)
                {
                    return ApiResult<SlaughterEnterpriseInfo>.Fail("无效的编号", ApiResultCode.Error);
                }

                if (string.IsNullOrWhiteSpace(request.CompanyName))
                {
                    return ApiResult<SlaughterEnterpriseInfo>.Fail("公司名称不能为空", ApiResultCode.Error);
                }

                if (string.IsNullOrWhiteSpace(request.CompanyAddress))
                {
                    return ApiResult<SlaughterEnterpriseInfo>.Fail("公司地址不能为空", ApiResultCode.Error);
                }

                // 检查记录是否存在
                var existingEntity = await _repository.GetByIdAsync(request.Id);
                if (existingEntity == null)
                {
                    return ApiResult<SlaughterEnterpriseInfo>.Fail("未找到对应的屠宰企业信息", ApiResultCode.NotFound);
                }

                // 更新实体信息
                existingEntity.CompanyName = request.CompanyName;
                existingEntity.CompanyAddress = request.CompanyAddress;
                existingEntity.CompanyDescription = request.CompanyDescription;
                existingEntity.EstablishmentDate = request.EstablishmentDate;
                existingEntity.BatchNo = request.BatchNo;

                // 保存到数据库
                await _repository.UpdateAsync(existingEntity);

                return ApiResult<SlaughterEnterpriseInfo>.Success(existingEntity, "修改成功");
            }
            catch (Exception ex)
            {
                return ApiResult<SlaughterEnterpriseInfo>.Fail($"修改失败: {ex.Message}", ApiResultCode.Error);
            }
        }
    }
} 